package com.maezia.tdr.dao.repository;

import com.maezia.tdr.common.CommonConstant;
import com.maezia.tdr.common.redis.BaseRedisRepository;
import com.maezia.tdr.dao.mapper.ReportFieldRelMapper;
import com.maezia.tdr.domain.po.Dict;
import com.maezia.tdr.domain.po.ReportFieldRel;
import com.maezia.tdr.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Repository
public class ReportFieldRelRepository extends BaseRedisRepository<ReportFieldRel> {

    private static String REPORT_FIELD_REL_INFO_KEY = "REPORT_FIELD_REL" ;

    @Autowired
    private ReportFieldRelMapper reportFieldRelMapper;

    @Autowired
    private DictService dictService;

    public ReportFieldRelRepository() {
        super(ReportFieldRel.class);
    }

    public List<ReportFieldRel> getByType(String clientId, int code) {
        String redisKey = REPORT_FIELD_REL_INFO_KEY + CommonConstant.COLON + clientId + CommonConstant.COLON + code;
        List<ReportFieldRel> relList = redisListOpsTemporary.range(redisKey, 0, -1);
        if(CollectionUtils.isEmpty(relList)){
            relList = reportFieldRelMapper.getByType(code);
            if(!CollectionUtils.isEmpty(relList)){
                save2List(relList);
            }
        }
        return relList;
    }

    private void save2List(List<ReportFieldRel> relList) {
        Dict dict = dictService.getByKey(REPORT_FIELD_REL_INFO_KEY);

        Set<String> typeKeys = relList.stream().map(type -> REPORT_FIELD_REL_INFO_KEY + CommonConstant.COLON + type.getClientId() +
                CommonConstant.COLON + type.getSourceType()).collect(Collectors.toSet());
        redisTemplateTemporary.delete(typeKeys);

        Map<String, List<ReportFieldRel>> typeMap = relList.stream().collect(Collectors.groupingBy(fieldRel -> fieldRel.getClientId() + CommonConstant.COLON + fieldRel.getSourceType()));
        if(!CollectionUtils.isEmpty(typeMap)){
            typeMap.forEach((k,v) -> {
                String redisKey = REPORT_FIELD_REL_INFO_KEY + CommonConstant.COLON + k;
                if(!redisTemplateTemporary.hasKey(redisKey)){
                    redisListOpsTemporary.rightPushAll(redisKey, v);
                    redisTemplateTemporary.expire(redisKey, Long.valueOf(dict.getValue()), TimeUnit.DAYS);
                }
            });
        }
    }
}
